package com.ht.graphmodel;

import com.ht.aems.ieeeformat.BusData;
import com.ht.aems.ieeeformat.DefaultIeeeDataParser;
import com.ht.aems.ieeeformat.IEEEDataIsland;
import com.ht.aems.ieeeformat.IslandTopoUtil;

import javax.swing.tree.DefaultMutableTreeNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @author Dong Shufeng
 *         Date: 2010-5-20
 */
public class IEEE2JTree {
    private static List<BusData> dataPassed = new ArrayList<BusData>();
    public static DefaultMutableTreeNode createTreeBridge(String ieeeFile) {
        DefaultIeeeDataParser parser = new DefaultIeeeDataParser();
        return createTreeBridge(parser.parse(ieeeFile));
    }

     public static IEEEDataIsland getIand(String ieeeFile) {
        DefaultIeeeDataParser parser = new DefaultIeeeDataParser();
        return parser.parse(ieeeFile);
    }

    public static DefaultMutableTreeNode createTreeBridge(IEEEDataIsland island) {
        Map<BusData, List<BusData>> bus2Buses = IslandTopoUtil.getBus2Buses(island);
        BusData rootBus = island.getBus(island.getSlackBusNum());
        DefaultMutableTreeNode root = new DefaultMutableTreeNode(rootBus.getName());
        dataPassed.clear();
        dataPassed.add(rootBus);
        List<BusData> busData = bus2Buses.get(rootBus);
        if (busData.size() > 0) {
            for (BusData bus : busData) {
                if (dataPassed.contains(bus))
                    continue;
                DefaultMutableTreeNode node = new DefaultMutableTreeNode(bus);
                root.add(node);
                dataPassed.add(bus);
                doNext(bus2Buses, bus, node);
            }
        }
        return root;
    }

    private static void doNext(Map<BusData, List<BusData>> bus2Buses, BusData rootBus, DefaultMutableTreeNode defaultMutableTreeNode) {
        List<BusData> busData = bus2Buses.get(rootBus);
        if (busData.size() > 0) {
            for (BusData bus : busData) {
                if (dataPassed.contains(bus))
                    continue;
                DefaultMutableTreeNode node = new DefaultMutableTreeNode(bus);
                defaultMutableTreeNode.add(node);
                dataPassed.add(bus);
                doNext(bus2Buses, bus, node);
            }
        }
    }
}
